package com.colouredglaze.filter;

import com.colouredglaze.entity.TbUser;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ZhangLin
 * @version 1.0
 * @date 2020/11/24 23:43
 */
@WebFilter(filterName = "UserPageFilter",urlPatterns = "/jsp/user/*")
public class UserPageFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws  IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        try{
            TbUser user= (TbUser) request.getSession().getAttribute("user");
            if(user.getRole()==0){
                chain.doFilter(req, resp);
            }else{
                request.setAttribute("msg", "请登录");
                response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
            }}catch (Exception e){
            request.setAttribute("msg", "请登录");
            response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
